﻿#ifndef _DATA_H
#define _DATA_H
#include "util.hpp"
#include<unordered_map>
#include<sstream>
namespace tqbcloud {
	class DataManager {
	private:
		std::unordered_map<std::string, std::string> _table;
		std::string _back_file;
	public:
		bool Split(const std::string & str,const std::string& sep,std::vector<std::string> *arr) {
			int index = 0;
			while (1) {
				int pos = str.find(sep,index);
				if (pos == std::string::npos) {
					break;
				}
				arr->push_back(str.substr(index,pos-index));
				index = pos + sep.size();
			}
			if (index < str.size()) {
				arr->push_back(str.substr(index));
			}
			return true;
		}
		DataManager(const std::string back_file) 
			:_back_file(back_file)
		{
			InitLoad();
		}
		bool InitLoad() {//程序运行时加载以前的数据
			tqbcloud::Fileutil fu(_back_file);
			if (!fu.Exists()) {
				std::cout<<"无初始化文件" << std::endl;
				return false;
			}
			std::string body;
			fu.GetContent(&body);
			std::vector<std::string> arr;
			Split(body,"\n",&arr);
			for (auto& i : arr) {
				std::vector<std::string> tmp;
				Split(i," ", &tmp);
				_table[tmp[0]] = tmp[1];
			}
			return true;
		}
		bool Storage() {
			std::stringstream ss;
			for (auto& i : _table) {
				ss << i.first << " " << i.second << "\n";
			}
			tqbcloud::Fileutil fu(_back_file);
			std::string tmp = ss.str();
			fu.SetContent(&tmp);
			return true;
		}
		bool Insert(const std::string& key, const std::string& val) {
			_table[key] = val;
			Storage();
			return true;
		}
		bool Update(const std::string& key, const std::string& val) {
			_table[key] = val;
			Storage();
			return true;
		}
		bool GetOneByKey(const std::string& key, std::string* val) {
			auto it=_table.find(key);
			if (it == _table.end()){
				return false;
			}
			*val = it->second;
			return true;
		}
	};
}
#endif
